package service

/**
 * Author: ycliud
 * Description: podservice
 * Date:20250927
 */

import (
	"fmt"
	"kubernate-server/conf"
	"net/http"

	corev1 "k8s.io/api/core/v1"

	pod_res "kubernate-server/module/pod/response"

	"github.com/gin-gonic/gin"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type PodService struct {
	nameSpace string `json:"nameSpace" binding:"required"`
	podName   string `json:"podName" binding:"required"`
}

type PodReq struct {
	Podname   string `json:"podname"  binding:"required"`
	Namespace string `json:"namespace" binding:"required"`
	Imagename string `json:"imagename" binding:"required"`
	Image     string `json:"image" binding:"required"`
}

/*
*	获取pod的详情信息
 */
func (*PodService) GetPodDetail(ctx *gin.Context) {
	//var err = conf.KuberConfigSet.CoreV1().Pods(ctx.Param("nameSpace")).Get(ctx, ctx.Param("nameSpace"))
	podDetail, err := conf.KuberConfigSet.CoreV1().Pods(ctx.Param("namespace")).Get(ctx, ctx.Param("podname"), metav1.GetOptions{})
	fmt.Println(ctx.Param("namespace"), ctx.Param("podname"))
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":       "2000",
		"messge":     "success",
		"name":       podDetail.Name,
		"namespace":  podDetail.Namespace,
		"status":     podDetail.Status.Phase,
		"containers": podDetail.Spec.Containers,
		"age":        podDetail.CreationTimestamp.Unix(),
		"IP":         podDetail.Status.PodIP,
		//"restarts":  podDetail.get,
		"node": podDetail.Spec.NodeName,
	})
}

/*
*	获取pod列表
 */
func (*PodService) GetPodList(ctx *gin.Context) {
	// ctx := context.TODO()
	list, err := conf.KuberConfigSet.CoreV1().Pods(ctx.Param("namespace")).List(ctx, metav1.ListOptions{})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	podList := make([]pod_res.PodListItem, 0)
	for _, item := range list.Items {
		podItem := PodK8s2ItemRes(item)
		podList = append(podList, podItem)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    20000,
		"messge":  "success",
		"podList": podList,
	})

}

func PodK8s2ItemRes(pod corev1.Pod) pod_res.PodListItem {

	var totalC, readyC, restartC int32
	for _, containerStatus := range pod.Status.ContainerStatuses {
		if containerStatus.Ready {
			readyC++
		}
		restartC += containerStatus.RestartCount
		totalC++
	}
	var podStatus string
	if pod.Status.Phase != "Running" {
		podStatus = "Error"
	} else {
		podStatus = "Running"
	}
	return pod_res.PodListItem{
		Name:     pod.Name,
		Ready:    fmt.Sprintf("%d/%d", readyC, totalC),
		Status:   podStatus,
		Restarts: restartC,
		Age:      pod.CreationTimestamp.Unix(),
		IP:       pod.Status.PodIP,
		Node:     pod.Spec.NodeName,
	}
}

/*
*	添加一个pod
 */
func (*PodService) CreatePod(ctx *gin.Context) {
	var req PodReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	_, error := conf.KuberConfigSet.CoreV1().Pods(req.Namespace).Create(ctx, creatPodReq2K8s(&req), metav1.CreateOptions{})
	if error != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":   20000,
		"messge": "success",
	})
}

// 转换k8s数据结构
func creatPodReq2K8s(req *PodReq) *corev1.Pod {
	return &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      req.Podname,
			Namespace: req.Namespace,
		},
		Spec: corev1.PodSpec{
			NodeSelector: nil,
			Affinity:     nil,
			Tolerations:  nil,
			Containers: []corev1.Container{
				{
					Name:  req.Imagename,
					Image: req.Image,
				},
			},
			Volumes:     nil,
			DNSConfig:   nil,
			HostAliases: nil,
		},
	}
}

/*
*	更新一个pod
 */
func (*PodService) UpdatePod(ctx *gin.Context) {
	var req PodReq
	// 1. 绑定并校验请求参数
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request: " + err.Error()})
		return
	}
	// 2. 校验关键参数非空
	if req.Namespace == "" || req.Podname == "" || req.Image == "" {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "namespace, podname, image are required"})
		return
	}

	// 3. 获取Pod并处理错误
	podNS := conf.KuberConfigSet.CoreV1().Pods(req.Namespace)
	newPodDetail, err := podNS.Get(ctx, req.Podname, metav1.GetOptions{})
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "pod not found: " + err.Error()})
		return
	}

	// 4. 更新注解（避免覆盖原有注解）
	if newPodDetail.Annotations == nil {
		newPodDetail.Annotations = make(map[string]string)
	}
	newPodDetail.Annotations["updated-by"] = "update pod"

	// 5. 更新容器信息（按容器名匹配，避免硬编码索引）
	containerFound := false
	for i, c := range newPodDetail.Spec.Containers {
		if c.Name == req.Imagename { // 假设req.Imagename是目标容器名
			newPodDetail.Spec.Containers[i].Image = req.Image
			containerFound = true
			break
		}
	}
	if !containerFound {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "container " + req.Imagename + " not found in pod"})
		return
	}

	// 6. 使用Update更新（若需部分更新建议改用Patch）
	_, err = podNS.Update(ctx, newPodDetail, metav1.UpdateOptions{})
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"message": "update failed",
			"error":   err.Error(),
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    20000,
		"message": "success", // 修正拼写错误
	})
}

/*
*	删除Pod
 */
func (*PodService) DeletePod(ctx *gin.Context) {
	var err = conf.KuberConfigSet.CoreV1().Pods(ctx.Param("namespace")).Delete(ctx, ctx.Param("podname"), metav1.DeleteOptions{})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":   20000,
		"messge": "success",
	})
}
